package net.expectx.common.single.util;

import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.management.ManagementFactory;

import com.sun.management.OperatingSystemMXBean;

/**
 * @author lijian
 * 监听当前系统运行信息
 */
public class MonitorCurrentSystemUtil {
    private static final int CPU_TIME = 5000;

    private static final int PERCENT = 100;

    private static final int FAULT_LENGTH = 10;

    private static final String OS_WINDOWS = "windows";
    private static final String STRING_WIN_DIR = "windir";

    /**
     * 获得当前的监控对象
     *
     * @return
     * @throws Exception
     */
    public MonitorCurrentSystemInfo getMonitorCurrentSystemInfo() {
        int kb = 1024;
        // 可使用内存
        long totalMemory = Runtime.getRuntime().totalMemory() / kb;
        // 剩余内存
        long freeMemory = Runtime.getRuntime().freeMemory() / kb;
        // 最大可使用内存
        long maxMemory = Runtime.getRuntime().maxMemory() / kb;

        OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();

        // 操作系统
        String osName = System.getProperty("os.name");
        // 总的物理内存
        long totalMemorySize = operatingSystemMXBean.getTotalPhysicalMemorySize() / kb;
        // 剩余的物理内存
        long freePhysicalMemorySize = operatingSystemMXBean.getFreePhysicalMemorySize() / kb;
        // 已使用的物理内存
        long usedMemory = (operatingSystemMXBean.getTotalPhysicalMemorySize() - operatingSystemMXBean.getFreePhysicalMemorySize()) / kb;

        // 获得线程总数
        ThreadGroup parentThread;
        for (parentThread = Thread.currentThread().getThreadGroup(); parentThread.getParent() != null; parentThread = parentThread.getParent()) {
        }

        int totalThread = parentThread.activeCount();
        double cpuRatio = 0;
        if (osName.toLowerCase().startsWith(OS_WINDOWS)) {
            cpuRatio = this.getCpuRatioForWindows();
        }

        // 构造返回对象
        MonitorCurrentSystemInfo currentSystemInfo = new MonitorCurrentSystemInfo();
        currentSystemInfo.setFreeMemory(freeMemory);
        currentSystemInfo.setFreePhysicalMemorySize(freePhysicalMemorySize);
        currentSystemInfo.setMaxMemory(maxMemory);
        currentSystemInfo.setOsName(osName);
        currentSystemInfo.setTotalMemory(totalMemory);
        currentSystemInfo.setTotalMemorySize(totalMemorySize);
        currentSystemInfo.setTotalThread(totalThread);
        currentSystemInfo.setUsedMemory(usedMemory);
        currentSystemInfo.setCpuRatio(cpuRatio);
        return currentSystemInfo;
    }

    /**
     * 获得CPU使用率
     *
     * @return
     */
    private double getCpuRatioForWindows() {
        try {
            String procCmd = System.getenv(STRING_WIN_DIR)
                    + "//system32//wbem//wmic.exe process get Caption,CommandLine,"
                    + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
            /**
             * 取进程信息
             */
            long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));
            Thread.sleep(CPU_TIME);
            long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
            if (c0 != null && c1 != null) {
                long idleTime = c1[0] - c0[0];
                long busyTime = c1[1] - c0[1];
                return Double.valueOf(PERCENT * (busyTime) / (busyTime + idleTime)).doubleValue();
            } else {
                return 0.0;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return 0.0;
        }
    }

    /**
     * 读取CPU信息
     *
     * @param proc
     * @return
     */
    private long[] readCpu(final Process proc) {
        long[] infos = new long[2];
        try {
            proc.getOutputStream().close();
            InputStreamReader ir = new InputStreamReader(proc.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String line = input.readLine();
            if (line == null || line.length() < FAULT_LENGTH) {
                return null;
            }
            int capIdX = line.indexOf("Caption");
            int cmdIdX = line.indexOf("CommandLine");
            int rocIdX = line.indexOf("ReadOperationCount");
            int umtIdX = line.indexOf("UserModeTime");
            int kmtIdX = line.indexOf("KernelModeTime");
            int wocIdX = line.indexOf("WriteOperationCount");
            long idleTime = 0;
            long kNelTime = 0;
            long userTime = 0;
            while ((line = input.readLine()) != null) {
                if (line.length() < wocIdX) {
                    continue;
                }
                String caption = substring(line, capIdX, cmdIdX - 1)
                        .trim();
                String cmd = substring(line, cmdIdX, kmtIdX - 1).trim();
                if (cmd.indexOf("wmic.exe") >= 0) {
                    continue;
                }
                if ("System Idle Process".equals(caption)
                        || "System".equals(caption)) {
                    idleTime += Long.valueOf(
                            substring(line, kmtIdX, rocIdX - 1).trim())
                            .longValue();
                    idleTime += Long.valueOf(
                            substring(line, umtIdX, wocIdX - 1).trim())
                            .longValue();
                    continue;
                }

                kNelTime += Long.valueOf(
                        substring(line, kmtIdX, rocIdX - 1).trim())
                        .longValue();
                userTime += Long.valueOf(
                        substring(line, umtIdX, wocIdX - 1).trim())
                        .longValue();
            }
            infos[0] = idleTime;
            infos[1] = kNelTime + userTime;
            return infos;
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                proc.getInputStream().close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String substring(String src, int startIdx, int endIdx) {
        byte[] b = src.getBytes();
        String tgt = "";
        for (int i = startIdx; i <= endIdx; i++) {
            tgt += (char) b[i];
        }
        return tgt;
    }

    public static void main(String[] args) throws Exception {
        MonitorCurrentSystemUtil service = new MonitorCurrentSystemUtil();
        MonitorCurrentSystemInfo monitorInfo = service.getMonitorCurrentSystemInfo();
        System.out.println("cpu占有率=" + monitorInfo.getCpuRatio());

        System.out.println("可使用内存=" + monitorInfo.getTotalMemory());
        System.out.println("剩余内存=" + monitorInfo.getFreeMemory());
        System.out.println("最大可使用内存=" + monitorInfo.getMaxMemory());

        System.out.println("操作系统=" + monitorInfo.getOsName());
        System.out.println("总的物理内存=" + monitorInfo.getTotalMemorySize() + "kb");
        System.out.println("剩余的物理内存=" + monitorInfo.getFreeMemory() + "kb");
        System.out.println("已使用的物理内存=" + monitorInfo.getUsedMemory() + "kb");
        System.out.println("线程总数=" + monitorInfo.getTotalThread() + "kb");
    }


    public class MonitorCurrentSystemInfo {
        /**
         * 可使用内存
         */
        private long totalMemory;

        /**
         * 剩余内存
         */
        private long freeMemory;

        /**
         * 最大可使用内存.
         */
        private long maxMemory;

        /**
         * 操作系统
         */
        private String osName;

        /**
         * 总的物理内存
         */
        private long totalMemorySize;

        /**
         * 剩余的物理内存
         */
        private long freePhysicalMemorySize;

        /**
         * 已使用的物理内存
         */
        private long usedMemory;

        /**
         * 线程总数
         */
        private int totalThread;

        /**
         * cpu使用率
         */
        private double cpuRatio;

        public long getFreeMemory() {
            return freeMemory;
        }

        public void setFreeMemory(long freeMemory) {
            this.freeMemory = freeMemory;
        }

        public long getFreePhysicalMemorySize() {
            return freePhysicalMemorySize;
        }

        public void setFreePhysicalMemorySize(long freePhysicalMemorySize) {
            this.freePhysicalMemorySize = freePhysicalMemorySize;
        }

        public long getMaxMemory() {
            return maxMemory;
        }

        public void setMaxMemory(long maxMemory) {
            this.maxMemory = maxMemory;
        }

        public String getOsName() {
            return osName;
        }

        public void setOsName(String osName) {
            this.osName = osName;
        }

        public long getTotalMemory() {
            return totalMemory;
        }

        public void setTotalMemory(long totalMemory) {
            this.totalMemory = totalMemory;
        }

        public long getTotalMemorySize() {
            return totalMemorySize;
        }

        public void setTotalMemorySize(long totalMemorySize) {
            this.totalMemorySize = totalMemorySize;
        }

        public int getTotalThread() {
            return totalThread;
        }

        public void setTotalThread(int totalThread) {
            this.totalThread = totalThread;
        }

        public long getUsedMemory() {
            return usedMemory;
        }

        public void setUsedMemory(long usedMemory) {
            this.usedMemory = usedMemory;
        }

        public double getCpuRatio() {
            return cpuRatio;
        }

        public void setCpuRatio(double cpuRatio) {
            this.cpuRatio = cpuRatio;
        }
    }
}
